# -*- coding: utf-8 -*-
import aiohttp
import asyncio
from aiohttp.formdata import FormData

"""
1.request请求参数
    url - request url
    params - (optional) Dictionary or bytes to be sent in the query string of the new request
    data - (optional) Dictionary, bytes, or file-like object to send in the body of the request
    json - (optional) Any json compatible python object headers
    cookies - (optional) Dict object to send with the request
    auth - (optional) BasicAuth named tuple represent HTTP Basic Auth auth - aiohttp.helpers.BasicAuth
    allow_redirects - (optional) If set to False, do not follow redirects
    proxy - 'http://127.0.0.1:8080'
    timeout - Optional ClientTimeout settings structure, 5min total timeout by default.

2.设置全局header和cookie
    aiohttp.ClientSession(headers={'a': '1'}, cookies={'b': '2'})

3.设置代理
    session.get(url='', proxy='http://127.0.0.1:8080')
"""


async def fetch(session, url):
    async with session.get(url=url) as res:
        text = await res.text()  # 获取二进制内容为response.read()
        print(text)


# 流式下载大文件
"""
1.不使用流式迭代器的写法
    with open(filename, 'wb') as fd:
    while True:
        chunk = await resp.content.read(chunk_size)
        if not chunk:
            break
        fd.write(chunk)
2.异步流式迭代器
    (1)按行读取
    async for line in response.content:
        print(line)
    (2)指定了最大可读字节的数据块迭代器
    async for data in response.content.iter_chunked(1024):
        print(data)
    (3)按顺序读取在流中的数据块:
    async for data in response.content.iter_any():
        print(data)
"""
async def download_steam(session, url, filepath):
    async with session.get(url) as res:
        file_size = res.content_length
        down_size = 0
        with open(filepath, 'wb') as fd:
            async for chunk in res.content.iter_chunked(8192):
                fd.write(chunk)
                down_size += len(chunk)
                print('\r下载进度：{:.2%}'.format(down_size / file_size), end='', flush=True)


# 普通下载
async def download(session, url, filepath):
    async with session.get(url) as res:
        with open(filepath, 'wb') as fd:
            fd.write(res.read())


# 文件上传
async def upload(session, url):
    files = FormData(quote_fields=False)  # 当上传文件时要设置为False,不然filename会被url编码
    files.add_field('file', open('a.txt', 'rb'), filename='#.txt', content_type='text/plain')
    files.add_field('a', '#')
    async with session.post(url=url, data=files, proxy='http://127.0.0.1:8080') as res:
        text = await res.text()
        print(text)


async def main():
    async with aiohttp.ClientSession() as session:
        await download_steam(session, 'https://api.vvhan.com/api/acgimg', 'a.jpg')


if __name__ == '__main__':
    # asyncio.run(main())
    asyncio.get_event_loop().run_until_complete(main())

